<template>
  <!-- 主体区域 -->
  <section id="app">
    <TodoHeader @add="onAdd"></TodoHeader>
    <TodoMain :list="list" @delete="onDelete"></TodoMain>
    <TodoFooter :list="list" @clear="onClear"></TodoFooter>
  </section>
</template>

<script>
import TodoHeader from "./components/TodoHeader.vue";
import TodoMain from "./components/TodoMain.vue";
import TodoFooter from "./components/TodoFooter.vue";

// 本地存储的Key
const dataKey = "xh-todos";

// 默认数据
const defaultList = [
  { id: 1, name: "打篮球" },
  { id: 2, name: "看电影" },
  { id: 3, name: "逛街" },
];

export default {
  data() {
    return {
      // 优先从本地存储中，获取数据
      list: JSON.parse(localStorage.getItem(dataKey)) || defaultList,
    };
  },
  methods: {
    // 处理添加
    onAdd(todoName) {
      this.list.unshift({
        id: Date.now(),
        name: todoName,
      });
    },
    // 处理删除
    onDelete(id) {
      const index = this.list.findIndex((item) => item.id === id);
      this.list.splice(index, 1);
    },
    // 清空
    onClear() {
      this.list = [];
    },
  },
  watch: {
    list: {
      // 深度监听
      deep: true,
      handler(newValue) {
        // 同步数据到本地存储
        localStorage.setItem(dataKey, JSON.stringify(newValue));
      },
    },
  },
  components: {
    TodoHeader,
    TodoMain,
    TodoFooter,
  },
};
</script>

<style>
</style>